<template>
    <div>
        <!-- 顶部 -->
        <div class="header">
            <div class="company-name">爱吃兔</div>
            <div class="user-info">
                <div>用户名：{{ username }}</div>
                <div>角色：{{ role }}</div>
                <div @click="logout">退出登录</div>
            </div>
        </div>
        <!-- 主体 -->
        <div class="main">
            <!-- 右侧菜单 -->
            <div class="right-menu">
                <div v-for="(navItem, navIndex) in navigation" :key="navIndex">
                    <div v-if="navItem.children && navItem.children.length > 0">
                        <div class="parent-menu-item" @click="toggleSubMenu(navIndex)">
                            <span :class="navItem.iconClass">{{ navItem.icon }}</span>
                            <span>{{ navItem.title }}</span>
                            <span
                                :class="{ 'arrow-up': subMenuVisible[navIndex], 'arrow-down': !subMenuVisible[navIndex] }"></span>
                        </div>
                        <div v-show="subMenuVisible[navIndex]" class="sub-menu">
                            <router-link v-for="(subItem, subIndex) in navItem.children" :key="subIndex"
                                :to="subItem.route" class="sub-menu-item">
                                {{ subItem.title }}
                            </router-link>
                        </div>
                    </div>
                    <router-link v-else :to="navItem.route" :class="navItem.iconClass" class="menu-item">
                        <span :class="navItem.iconClass">{{ navItem.icon }}</span>
                        <span>{{ navItem.title }}</span>
                    </router-link>
                </div>
            </div>
            <!-- 左侧内容 -->
            <div class="left-content">
                <el-button type="success" style="margin-bottom: 10px;" @click="open(null)">增加</el-button>
                <el-table :data="teee" style="width: 1000px;height: 550px;">
                    <el-table-column type="selection" width="50" />
                    <el-table-column type="index" width="55" label="序号" />
                    <el-table-column prop="goodsId" label="生产名称" />
                    <el-table-column prop="productionbatches" label="生产批次" />
                    <el-table-column prop="shelflifeDay" label="保质期（天）" />
                    <el-table-column prop="productionlicense" label="生产许可证" />
                    <el-table-column prop="productionCompany" label="生产企业" />
                    <el-table-column fixed="right" label="操作" min-width="120">
                        <template v-slot="scope">
                            <el-button link type="primary" size="small" @click="del(scope.row)">
                                删除
                            </el-button>
                            <el-button link type="primary" size="small" @click="open(scope.row)">详情</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination v-model:current-page="from.pageIndex" v-model:page-size="from.pageSize"
                    :page-sizes="[10, 20, 30]" :background="true" layout="total, sizes, prev, pager, next, jumper"
                    :total="from.recordCount" />
            </div>
        </div>
        <div>
            <el-dialog v-model="logic.isOpen" title="基本信息" width="500">
                <el-form :model="consid" width-label="200px">
                    <el-form-item label="商品名称: ">
                        <el-input v-model="consid.goodsId" />
                    </el-form-item>
                    <el-form-item label="生产批次: ">
                        <el-input v-model="consid.productionbatches" />
                    </el-form-item>
                    <el-form-item label="保质期（天）: ">
                        <el-input v-model="consid.shelflifeDay" />
                    </el-form-item>
                    <el-form-item label="生产许可证号: ">
                        <el-input v-model="consid.productionlicense" />
                    </el-form-item>
                    <el-form-item label="生产企业: ">
                        <el-input v-model="consid.productionCompany" />
                    </el-form-item>
                    <el-form-item label="封面图: ">
                        <!--上传图片-->
                        <el-upload class="avatar-uploader"
                            action="http://localhost:5080/api/User/UploadImages/UploadImages" :show-file-list="true"
                            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                            :on-change="handleFileChange">
                            <img v-if="previewUrl" :src="previewUrl" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="logic.isOpen = false">取消</el-button>
                        <el-button type="primary" @click="addTrace()">
                            添加
                        </el-button>
                    </div>
                </template>
            </el-dialog>

        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch, toRefs } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'


const router = useRouter()
const route = useRoute()

// 定义 UploadProps 类型
type UploadProps = {
    onSuccess: (response: any, uploadFile: any) => void;
    beforeUpload: (rawFile: any) => boolean;
};

//分页
const from = reactive({
    pageIndex: 1,
    pageSize: 10,
    recordCount: 1,
    pageCount: 1
})
//上传图片
const consid = reactive({
    trId: 0,
    goodsId: "",
    productionbatches: "",
    shelflifeDay: "",
    productionlicense: "",
    productionCompany: "",
    coverimage: "",
})
const logic = reactive({
    isOpen: false,
    isAdd: true
})
// 用户信息
const username = ref('张三');
const role = ref('管理员');

// 导航菜单数据
const navigation = ref([
    {
        title: '溯源管理',
        icon: '1.',
        iconClass: '',
        children: [
            { title: 'item one', route: '/menu1' },
            { title: 'item two', route: '/menu2' },
        ]
    },
    {
        title: '溯源管理-养殖信息',
        icon: '2.',
        iconClass: '',
        children: [
            { title: 'item one', route: '/menu1' },
            { title: 'item two', route: '/menu2' },
        ]
    },
    {
        title: '溯源管理-屠宰信息',
        icon: '3.',
        iconClass: '',
        children: [
            { title: 'item one', route: '/menu1' },
            { title: 'item two', route: '/menu2' },
        ]
    },
    {
        title: '溯源管理-深加工信息',
        icon: '4.',
        iconClass: '',
        children: [
            { title: 'item one', route: '/menu1' },
            { title: 'item two', route: '/menu2' },
        ]
    }
]);

// 记录子菜单是否可见的状态
const subMenuVisible = ref(new Array(navigation.value.length).fill(false));

// 切换子菜单可见状态的方法
const toggleSubMenu = (index: number) => {
    subMenuVisible.value[index] = !subMenuVisible.value[index];
};
//上传图片
const imageUrl = ref('')
const previewUrl = ref('')
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    consid.coverimage = response;
    previewUrl.value = URL.createObjectURL(uploadFile.raw!)
}
//上传图片
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    console.log('Before upload - File:', rawFile);
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('必须是JPG 格式!');
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('不能超过 2MB!');
        return false;
    }
    return true;
};

const handleFileChange = (file: any) => {
    const reader = new FileReader();
    reader.onload = (e) => {
        previewUrl.value = e.target?.result as string;
    };
    reader.readAsDataURL(file.raw);
};

//表格显示
const teee = ref([])
const Gettable = () => {
    axios.get("http://localhost:5080/api/User/TranceShow", {
        params: {
            pageIndex: from.pageIndex,
            pageSize: from.pageSize
        }
    }).then(res => {
        teee.value = res.data.data.list

        from.recordCount = res.data.data.recordCount
        from.pageCount = res.data.data.pageCount
    })
}
//添加
const addTrace = () => {
    if (consid.goodsId == "") {
        ElMessage.error("商品名称不能为空")
        return
    }
    if (consid.productionbatches == "") {
        ElMessage.error("生产批次不能为空")
        return
    }
    if (consid.shelflifeDay == "") {
        ElMessage.error("保质期不能为空")
        return
    }
    if (consid.productionlicense == "") {
        ElMessage.error("生产许可证号不能为空")
        return
    }
    if (consid.productionCompany == "") {
        ElMessage.error("生产企业不能为空")
        return
    }
    if (consid.coverimage == "") {
        ElMessage.error("封面图不能为空")
        return
    }
    axios.post("http://localhost:5080/api/User/AddTrance", consid).then(res => {
        if (res.data.code == 300) {
            ElMessage.success(res.data.message)
            logic.isOpen = false
            Gettable()
        }
        else {
            ElMessage.error(res.data.message)
            return
        }
    })
}

const open = (row: any) => {
    logic.isOpen = true
    if (row == null) {
        logic.isAdd = true

        consid.trId = 0
        consid.goodsId = "";
        consid.productionbatches = "";
        consid.shelflifeDay = "";
        consid.productionlicense = "";
        consid.productionCompany = "";
        consid.coverimage = "";
        previewUrl.value = ''; // 确保在增加模式下清除图片路径
    }
    else {
        logic.isAdd = false

        consid.trId = row.trId;
        consid.goodsId = row.goodsId;
        consid.productionbatches = row.productionbatches;
        consid.shelflifeDay = row.shelflifeDay;
        consid.productionlicense = row.productionlicense;
        consid.productionCompany = row.productionCompany;


        // 添加调试信息，确保 row.coverimage 的值正确
        console.log('Cover image URL:', row.coverimage);

        // 确保 previewUrl 设置为正确的图片 URL
        previewUrl.value = row.coverimage; // 如果 coverimage 是一个有效的 URL 或路径，这行代码应该可以工作
        router.push({
            name: 'Show1',
            params: {
                trId: row.trId
            }
        })
    }
}
//删除
const del = (row: any) => {
    ElMessageBox.confirm(
        '确认删除吗?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            axios.post("http://localhost:5080/api/User/DelTrance", row).then(res => {
                if (res.data.code == 400) {
                    ElMessage.success(res.data.message)
                    Gettable()
                }
                else {
                    ElMessage.error(res.data.message)
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: 'Delete canceled',
            })
        })
}

watch(from, () => {
    Gettable()
})

onMounted(() => {
    Gettable()
})

// 退出登录方法
const logout = () => {
    // 这里可以添加退出登录的逻辑，例如清除 token 等
    router.push('/');
    //console.log('用户已退出登录');
};
</script>

<style scoped>
html,
body {
    height: 100vh;
    width: 100vw;
    margin: 0;
    padding: 0;
    overflow: hidden;
}

#app {
    height: 100vh;
    width: 100vw;
}

.main {
    display: flex;
    height: 800px;
    width: 100%;
}

.left-content {
    flex: 3;
    background-color: #f0f0f0;
    padding: 20px;
    overflow-y: auto;
}

.right-menu {
    flex: 1;
    background-color: #ddd;
    padding: 20px;
    overflow-y: auto;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #333;
    color: white;
    padding: 10px 20px;
    height: auto;
    height: 70px;
}

/* 公司名称 */
.company-name {
    font-size: 20px;
}

/* 用户相关信息 */
.user-info {
    display: flex;
    align-items: center;
}

.user-info div {
    margin-left: 15px;
}

.menu-item {
    margin-bottom: 15px;
    cursor: pointer;
    color: #007bff;
    text-decoration: none;
    display: flex;
    align-items: center;
}

.menu-item span:first-child {
    margin-right: 10px;
}

.parent-menu-item {
    margin-bottom: 15px;
    cursor: pointer;
    color: #000;
    text-decoration: none;
    display: flex;
    align-items: center;
}

.parent-menu-item span:first-child {
    margin-right: 10px;
}

.arrow-up,
.arrow-down {
    margin-left: auto;
    transition: transform 0.3s ease;
}

.arrow-up {
    transform: rotate(180deg);
}

.sub-menu {
    margin-left: 20px;
}

.sub-menu-item {
    display: block;
    margin-bottom: 5px;
    color: #007bff;
    text-decoration: none;
}

.sub-menu-item:hover {
    text-decoration: underline;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>